<template>
  <div class="container">
    <van-nav-bar title="隔离品处置" fixed class="titleStyle" left-arrow @click-left="onClickLeft" />
    <div class="publicBox formStyle">
      <van-row type="flex" justify="end" style="margin-bottom:10px;">
        <van-button style="width:80px" size="small" type="info" native-type="submit" :disabled="!submitData.testResult" @click="submitForm">提 交</van-button>
      </van-row>
      <van-cell-group style="margin-bottom:5px;">
        <van-field v-model="reworkNo" label="返工返修单号" placeholder="请扫描返工返修单号" right-icon="scan" @click-right-icon="scan" @keyup.enter.native="getDataByreworkNo(reworkNo)" />
      </van-cell-group>
      <div v-if="isShowForm" class="inputBox">
        <div style="margin-bottom:5px;">
          <van-form class="vanForm" label-width="80px" label-align="right">
            <van-collapse v-model="activeNames">
              <van-collapse-item name="1">
                <template #title>
                  <div>工单批次号 <span style="margin-left:20px;">{{ ruleForm.planBatchNo }}</span></div>
                </template>
                <van-row>
                  <van-col :span="24">
                    <van-field v-model="ruleForm.registerTime" readonly label="隔离时间" />
                  </van-col>
                  <van-col :span="24">
                    <van-field v-model="ruleForm.materialCode" readonly label="料号" />
                  </van-col>
                  <van-col :span="24">
                    <van-field v-model="ruleForm.materialName" readonly label="品名" />
                  </van-col>
                  <van-col :span="24">
                    <van-field v-model="ruleForm.proLineName" readonly label="报工产线" />
                  </van-col>
                  <van-col :span="12">
                    <van-field v-model="ruleForm.procedureName" readonly label="断点工序" placeholder="请选择工序" />
                  </van-col>
                  <van-col :span="12">
                    <van-field v-model="ruleForm.factoryName" label="报工工位" readonly />
                  </van-col>
                  <van-col :span="12">
                    <van-field :value="`${ruleForm.badNum} / ${ruleForm.registerNum}`" label="隔离数/总数" readonly />
                  </van-col>
                  <van-col :span="12">
                    <van-field :value="ruleForm.handledNum || 0" label="已处置数" readonly />
                  </van-col>
                  <van-col :span="12">
                    <van-field :value="ruleForm.badNum - (ruleForm.handledNum || 0)" readonly type="digit" label="待处置数" placeholder="请输入待处置数" />
                  </van-col>
                </van-row>
              </van-collapse-item>
            </van-collapse>
          </van-form>
        </div>
      </div>
      <!-- 检验结果 -->
      <div v-if="isShowForm" class="checkResult">
        <van-row>
          <van-col :span="12">
            <van-field v-model="submitData.judgmentNum" label-width="80px" label="判定数量" type="digit" class="mustInput" placeholder="请输入判定数量" />
          </van-col>
          <van-col :span="12">
            <van-field label="检验结果" class="mustInput">
              <template #input>
                <van-dropdown-menu>
                  <van-dropdown-item v-model="submitData.testResult" :options="checkResultList" />
                </van-dropdown-menu>
              </template>
            </van-field>
          </van-col>
          <van-col v-show="[2,3].includes(submitData.testResult)" :span="24">
            <defectSelectBox ref="defectSelectBox" v-model="submitData.defectId" placeholder="请选择缺陷项" :columns="defectsList" :option="{label:'defectName',value:'defectId'}" @confirm="selectDefects" />
          </van-col>
          <van-col v-if="submitData.testResult === 2" :span="24">
            <van-field v-model="submitData.proLineName" class="mustInput" readonly label="返工产线" placeholder="请选择产线" @focus="showProLineSelect = true" />
          </van-col>
          <van-col v-if="submitData.testResult === 2" :span="24">
            <van-field v-model="ruleForm.proLineName" style="margin-bottom:10px;" class="mustInput" readonly label="再加工产线" placeholder="请选择产线" />
          </van-col>
        </van-row>
      </div>
      <van-row class="procedureBox">
        <van-tabs v-if="submitData.testResult === 2 && submitData.proLineId" v-model="tabActive" type="card" color="#022566">
          <van-tab title="返工/返修工序" name="1">
            <div v-for="(item,index) in backProcedureList" :key="index" class="list">
              <ul>
                <li>
                  <van-field v-model="item.procedureName" label-width="60px" class="mustInput" readonly label="工序" placeholder="请选择工序" />
                </li>
                <li>
                  <van-field v-model="item.factoryName" label-width="60px" class="mustInput" readonly label="工位" placeholder="请选择工位" />
                </li>
                <li>
                  <van-row>
                    <van-col :span="24">
                      <van-field label-width="60px" name="stepper" label="加工顺序">
                        <template #input>
                          <van-stepper v-model="item.sort" button-size="22" integer step="10" min="10" />
                        </template>
                      </van-field>
                      <!-- <van-field v-model="item.sort" type="digit" class="mustInput" label="加工顺序" placeholder="请输入加工顺序" /> -->
                    </van-col>
                    <!-- <van-col :span="12">
                      <van-field label="报工点" class="mustInput">
                        <template #input>
                          <van-dropdown-menu>
                            <van-dropdown-item v-model="item.isPoint" :options="reportList" />
                          </van-dropdown-menu>
                        </template>
                      </van-field>
                    </van-col> -->
                  </van-row>
                </li>
              </ul>
              <van-row class="rightBtn">
                <!-- <van-icon name="delete" @click="list.splice(index,1)" /> -->
                <van-checkbox v-model="item.checked" icon-size="24px" shape="square" />
              </van-row>
            </div>
          </van-tab>
          <van-tab title="再加工工序" name="2">
            <div v-for="(item,index) in aGainWorkProcedureList" :key="index" class="list">
              <ul>
                <li>
                  <van-field v-model="item.procedureName" label-width="60px" class="mustInput" readonly label="工序" placeholder="请选择工序" />
                </li>
                <li>
                  <van-field v-model="item.factoryName" label-width="60px" class="mustInput" readonly label="工位" placeholder="请选择工位" />
                </li>
                <li>
                  <van-row>
                    <van-col :span="12">
                      <van-field v-model="item.sort" label-width="60px" readonly type="digit" label="加工顺序" class="mustInput" />
                    </van-col>
                    <van-col :span="12">
                      <van-field label="报工点" class="mustInput">
                        <template #input>
                          <van-dropdown-menu>
                            <van-dropdown-item v-model="item.isPoint" :options="reportList" />
                          </van-dropdown-menu>
                        </template>
                      </van-field>
                    </van-col>
                  </van-row>
                </li>
              </ul>
              <van-row class="rightBtn">
                <!-- <van-icon name="delete" @click="list.splice(index,1)" /> -->
                <van-checkbox v-model="item.checked" :disabled="item.isReprocessing === 1" icon-size="24px" shape="square" />
              </van-row>
            </div>
          </van-tab>
        </van-tabs>
      </van-row>
    </div>

    <!-- 返工返修产线 -->
    <van-popup v-model="showProLineSelect" position="bottom" :style="{ height: '30%' }">
      <van-picker title="产线选择" show-toolbar :columns="proLineList.map(item=>`${item.factoryName}`).filter(item=>!proLineFilterText || item.toLowerCase().includes(proLineFilterText.toLowerCase()))" @confirm="selectProLine" @cancel="showProLineSelect = false">
        <template slot="title">
          <van-search v-model="proLineFilterText" style="width:70%" placeholder="请输入产线名称" @clear=" proLineFilterText = ''" />
        </template>
      </van-picker>
    </van-popup>
  </div>
</template>
<script>
import defectSelectBox from './components/selectMultip'

export default {
  name: 'FirstInspection',
  components: { defectSelectBox },
  data () {
    return {
      activeNames: ['1'], // 表单折叠面板
      tabActive: '1',
      ruleForm: {
        testResult: '', // 检验结果
        isReport: ''
      },
      submitData: {
        defectId: [],
        testResult: '',
        judgmentNum: null,
        defectList: []
      },
      checkResultList: [
        { text: '请选择', value: '' },
        { text: '合格', value: 1 },
        { text: '返工返修', value: 2 },
        { text: '报废', value: 3 }
      ],
      reportList: [
        { text: '是', value: 1 },
        { text: '否', value: 0 }
      ],
      loading: false,
      reworkNo: '', // FX20240910003
      defectsList: [], // 缺陷项
      selectValue: [],
      isShowForm: false, // 未发起请求时不展示所有内容
      proLineFilterText: '',
      proLineList: [], // 返工返修产线list
      showProLineSelect: false,
      backProcedureList: [], // 返工返修工序list
      aGainWorkProcedureList: [] // 再加工工序list
    }
  },
  watch: {
  	'submitData.judgmentNum': {
  		handler (newVal, oldVal) {
        if (newVal > this.ruleForm.registerNum) {
          this.submitData.judgmentNum = this.ruleForm.registerNum
        }
  		},
  		immediate: true,
       	deep: true // 可以深度检测到  对象的属性值的变化
  	}
  },
  created () {
    const { code } = this.$route.params
    if (code) {
      this.planBatchNo = this.$route.params.code
      this.getDataByreworkNo(code)
    }
  },
  async mounted () {
    this.getBackProLineList()
    this.getDefectsList()
  },

  methods: {
    /**
     * @description: 扫码
     * @param {*} e
     * @return {*}
     */
    scan () {
      this.$router.push('/saomaShow?name=隔离品处置')
    },

    /**
     * @description: 根据工单批次号查询信息
     * @param {*} reworkNo
     * @return {*}
     */
    async getDataByreworkNo (reworkNo) {
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '数据加载中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      setTimeout(() => {
        toast.clear()
      }, 500)
      this.isShowForm = false
      this.resetForm()
      const res = await this.$axios.post(`/dobo-product/web/quarantine/record/selectDetailByDefectiveNo?reworkNo=${reworkNo}`)
      if (res?.data.code === 200) {
        // todo
        this.ruleForm = { ...this.ruleForm, ...res.data.data }
        this.submitData.judgmentNum = this.ruleForm.badNum - (this.ruleForm.handledNum || 0)
        this.isShowForm = true
        this.submitData.defectId = this.ruleForm.defectList.map(item => item.defectId)
        this.submitData.defectList = this.defectsList.filter(item => this.submitData.defectId.includes(item.defectId))
      } else {
        this.isShowForm = false
      }
    },
    resetForm () {
      this.submitData = {
        defectId: [],
        testResult: '',
        judgmentNum: null,
        defectList: []
      }
      this.selectValue = []
      this.proLineFilterText = '',
      this.showProLineSelect = false
      this.backProcedureList = [] // 返工返修工序list
      this.aGainWorkProcedureList = [] // 再加工工序list
    },
    /**
    * @description:查询缺陷项列表
    * @return {*}
    */
    async getDefectsList () {
      const res = await this.$axios.get('/dobo-product/pro/patrol/check/defectsList')
      if (res?.data.code === 200) {
        this.defectsList = res.data.data
      }
    },
    /**
     * @description: 选中缺陷项
     * @param {*} val
     * @return {*}
     */
    selectDefects (val) {
      this.submitData.defectId = val
      this.submitData.defectList = this.defectsList.filter(item => val.includes(item.defectId))
    },
    /**
     * @description: 获取返修产线list
     * @return {*}
     */
    async getBackProLineList () {
      const res = await this.$axios.get('/dobo-product/factory/factoryListProLine')
      if (res?.data.code === 200) {
        this.proLineList = res.data.data
      }
    },
    /**
     * @description: 产线选中
     * @return {*}
     */
    async selectProLine (val) {
      const { factoryName, id } = this.proLineList.find(item => item.factoryName === val)
      this.submitData = { ...this.submitData, proLineName: factoryName, proLineId: id }
      this.showProLineSelect = false
      this.backProcedureList = await this.getProcedureListByFactoryId(id, 1)
      if (this.ruleForm.proLineId) {
        this.aGainWorkProcedureList = await this.getProcedureListByFactoryId(this.ruleForm.proLineId, 2)
      }
    },
    /**
     * @description: 根据选中的工序id获取工序LIST
     * @param {*} id
     * @param {*} type  1:返修返工 2:再加工
     * @return {*}
     */
    async getProcedureListByFactoryId (id, type) {
      const res = await this.$axios.get(`/dobo-product/web/quarantine/record/procedureReworkList?factoryId=${id}&type=${type}&planId=${this.ruleForm.planId}`)
      if (res?.data.code === 200) {
        res.data.data.forEach((item, index) => {
          item.itemType = type
          if (type === 2) {
            item.sort = (this.backProcedureList.length + 1 + index) * 10
            item.itemType = item.isReprocessing ? 2 : 3 // 3表示工序来源为工单下工艺工序
          } else {
            item.sort = (index + 1) * 10
          }
          item.mainId = item.procedureId
          item.checked = item.isReprocessing === 1 ? 1 : 0
          // item.checked = item.isPoint === 0
        })
        return res.data.data
      }
    },
    // 提交表单
    submitForm () {
      this.$dialog
        .confirm({
          title: '提示',
          message: '是否确认提交？'
        })
        .then(() => {
          // todo  backProcedureList aGainWorkProcedureList
          const { id } = this.ruleForm
          const { testResult, proLineId, proLineName, defectList, judgmentNum } = this.submitData
          let params = {
            testResult, quarantineManagementId: id, judgmentNum, reworkNo: this.reworkNo
          }
          if (judgmentNum > (this.ruleForm.badNum - (this.ruleForm.handledNum || 0))) {
            return this.$dialog.alert({ title: '提示', message: '本次处置数不能大于待处置数!' })
          }
          if ((testResult === 2 || testResult === 3) && defectList && defectList.length < 1) { // 返工返修 / 报废
            return this.$dialog.alert({ title: '提示', message: '请至少选中一条缺陷项!' })
          }

          if (testResult === 2) { // 返工返修
            if (!proLineId) {
              return this.$dialog.alert({ title: '提示', message: '请选择返工返修产线!' })
            }

            const backProcedureList = this.backProcedureList.filter(item => item.checked)
            const aGainWorkProcedureList = this.aGainWorkProcedureList.filter(item => item.checked && item.isReprocessing !== 1)

            if (backProcedureList.length < 1) {
              return this.$dialog.alert({ title: '提示', message: '请至少选中一条返工返修工序!' })
            }

            if ([...new Set(backProcedureList.map(item => item.sort))].length !== backProcedureList.length) {
              return this.$dialog.alert({ title: '提示', message: '选中返工返修工序加工顺序不能重复!' })
            }

            if (aGainWorkProcedureList.length < 1) {
              return this.$dialog.alert({ title: '提示', message: '请至少选中一条再加工工序!' })
            }

            params = {
              ...params,
              proLineId,
              proLineName,
              defectList,
              itemList: [...backProcedureList, ...this.aGainWorkProcedureList.filter(item => item.checked)]
            }
          }

          if (testResult === 3) {
            params = {
              ...params,
              defectList
            }
          }
          this.submitApi(params)
          console.log(params)
        })
        .catch(() => {
          return false
        })
    },
    submitApi (params) {
      this.$axios.post('/dobo-product/web/quarantine/record/save', params).then(res => {
		  console.log(res.data)
        if (res.data.code === 200) {
          this.$dialog
            .alert({
              title: '提示',
              message: '提交成功!'
            })
            .then(() => {
              window.location.reload()
            })
            .catch(() => { })
        } else {
          this.$toast.fail(res.data.msg)
          setTimeout(() => {
            window.location.reload()
          }, 1000)
        }
      })
    },
    // 返回
    onClickLeft () {
      const { query } = this.$route
      if (query.path) {
        this.$router.push(`/${query.path}`)
      } else {
        this.$router.push('/task')
      }
    }
  }
}
</script>
<style lang='scss' scoped>
.container {
  .publicBox {
    .vanForm {
      .van-field {
        border-bottom: 1px solid #ebedf0;
      }
      .zhedie {
        height: 45px;
        line-height: 45px;
        background: green;
        width: 100%;
        text-align: center;
      }
    }
  }
  .procedureBox {
    margin-top: 10px;
    .van-tab__pane {
      height: calc(63vh - 10px);
      background: #eee;
      margin-top: 10px;
      overflow-y: auto;
      border-radius: 3px;
      padding: 10px;
    }
    .list {
      display: flex;
      justify-content: space-between;
      ul {
        margin-bottom: 10px;
        width: calc(100% - 40px);
      }
    }
  }
}
</style>
<style lang='scss'>
.container {
  .publicBox {
    .checkResult,
    .procedureBox {
      //   height: calc(100% - 360px);
      //   overflow: hidden;
      .van-dropdown-menu__bar,
      .van-dropdown-menu {
        height: 100% !important;
        width: 100%;
        box-shadow: none;

        .van-dropdown-menu__item {
          justify-content: flex-start;
        }
      }
      .van-col--12 {
        .van-dropdown-item__content {
          width: 50%;
          left: 50%;
        }
      }
      .van-col--24 {
        .van-dropdown-item__content {
          width: 100%;
          left: 0px;
        }
      }
      .van-field {
        border-bottom: 1px solid #ebedf0;
      }
    }
  }
}

.procedureBox {
  .list {
    .van-dropdown-item__content {
      width: calc(100% - 140px);
      left: 20px;
    }
    .van-col--12 {
      .van-dropdown-item__content {
        width: calc(50% - 50px) !important;
        left: calc(50% - 30px) !important;
      }
    }
    .rightBtn {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      .van-icon-delete {
        font-size: 32px;
        color: #fa0000;
        margin-bottom: 40px;
      }
    }
  }
}
</style>
